var http = require("http");
var WebSocket = require('faye-websocket');

function get(remote, apiPath, callback) {
	http.request({
		host : remote.host,
		port : remote.port,
		path : apiPath
	}, function(res) {
		var data = '';
		res.on('data', function(chunk) {
			data += chunk;
		});
		res.on('end', function() {
			callback(null, JSON.parse(data));
		});
	}).end();
};

get({host: "localhost", port: 8080}, "/auth?userId=1&password=1", function(err, ret) {
	console.log(err);
	console.log(ret);
	if (ret.success) {
		var ws = new WebSocket.Client("ws://localhost:8080/chats?token="+ret.token);

		ws.on('open', function(event) {
		console.log('open');
		// @ForEleven 的测试是误导的
		// ws.send('Hello, world!');		
		setTimeout(function(){
			// 向下面这样构建一条聊天消息
			var msg = {};
			msg.type = "textMsg";
			msg.timestamp = new Date();
			msg.data = {};
			msg.data.to = "2";
			msg.data.from = "1";
			msg.data.msg = "hello";
			msg.data.id = "fd718190-2eba-4892-94f0-fff9c23d574e";	// UUID, 以后使用node.js uuid
			
			ws.send(JSON.stringify(msg));
		}, 1000)	
		});

		ws.on('message', function(event) {
		  console.log('message', event.data);
		});

		ws.on('close', function(event) {
		  console.log('close', event.code, event.reason);
		  ws = null;
		});
	}
});
